<?php

namespace frontend\controllers;

use common\widgets\Alert;
use frontend\models\Address;
use frontend\models\ddAddress;
use frontend\models\EveryIsOk;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;

class AddressController extends \yii\web\Controller
{
    /**
     * 通过acf实现权限控制
     */
    public function behaviors()
    {
        return [
            'acf'=>[
                'class'=>AccessControl::className(),
                'rules'=>[
                    [
                        'allow'=>true,
                        'actions'=>['index','list','edit','del','set-defualt'],
                        'roles'=>['@'],//登录用户
                    ],
                    [
                        'allow'=>true,
                        'actions'=>['index'],
                        'roles'=>['?'],//游客
                    ],
                ],
            ]
        ];
    }

    /**
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }


    public function actionList(){
        //实例化表单模型
        $models = Address::find()->where(['member_id'=>\Yii::$app->user->id])->all();
        $address = new Address();
        if($address->load(\Yii::$app->request->post()) && $address->validate()){
            //保存数据
            $address->member_id = \Yii::$app->user->identity->getId();
            $address->save();
            if($address->status==1){
               //调用方法设置默认值
                Address::defualtAddress($address->id);
            }
            return $this->refresh();
        }

       return $this->render('list',['models'=>$models,'address'=>$address]);
    }

    public function actionEdit($id){
        $model = Address::findOne(['id'=>$id]);
         if($model->load(\Yii::$app->request->post()) && $model->validate()){
            //保存数据
            $model->save();
            if($model->status==1){
               //调用方法设置默认值
                Address::defualtAddress($model->id);
            }
            return $this->redirect(['address/list']);
        }
        return $this->render('list',['address'=>$model]);
    }

    /**
     * @param $id
     * @return \yii\web\Response
     */
    public function actionDel($id){
        //删除收货地址
        $rs = ddAddress::findOne(['id'=>$id])->delete();
        return $this->redirect(['address/list']);
    }

    /**
     * @param $id
     * @return \yii\web\Response
     */
    public function actionSetDefault($id){
        //调用方法设置默认值
        Address::defualtAddress($id);
        return $this->redirect(['address/list']);

    }
}
